package cn.com.coding.app;

import cn.com.coding.common.lang.Const;
import cn.com.coding.common.lang.ResT;
import cn.com.coding.common.utils.PageUtil;
import cn.com.coding.system.domin.SysRoleEntity;
import cn.com.coding.system.domin.SysUserEntity;
import cn.com.coding.system.domin.SysUserRoleEntity;
import cn.com.coding.system.domin.dto.PassDto;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author mxz
 */
@RestController
@RequestMapping("cat/sysuser")
public class SysUserController extends BaseController {

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public ResT list(@RequestParam Map<String, Object> params) {
        PageUtil page = sysUserService.queryPage(params);

        return ResT.ok().put("page", page);
    }

    /**
     * 获取登陆人员信息
     */
    @RequestMapping("/info")
    public ResT info(Principal principal) {
        SysUserEntity sysUserEntity = sysUserService.getByUserName(principal.getName());
        SysUserEntity sysUser = sysUserService.getById(sysUserEntity.getPid());

        return ResT.ok().setData(MapUtil.builder()
                .put("sysUser", sysUser)
                .build());
    }

    /**
     * 获取某个管理员信息
     *
     * @param pid
     * @return
     */
    @RequestMapping("/info/{pid}")
    public ResT userInfo(@PathVariable("pid") String pid) {

        SysUserEntity sysUserEntity = sysUserService.getById(pid);

        List<SysRoleEntity> roles = sysRoleService.listRolesByUserPid(pid);

        sysUserEntity.setSysRoles(roles);

        return ResT.ok().setData(MapUtil.builder()
                .put("sysUser", sysUserEntity)
                .build());
    }

    /**
     * 重置密码
     *
     * @param pid
     * @return
     */
    @RequestMapping("/reset/{pid}")
    public ResT resetPassword(@PathVariable("pid") String pid) {
        SysUserEntity sysUserEntity = sysUserService.getById(pid);
        sysUserEntity.setPassword(bCryptPasswordEncoder.encode(Const.DEFULT_PASSWORD));
        sysUserEntity.setUpdateTime(new Date());
        sysUserService.updateById(sysUserEntity);
        return ResT.ok();
    }

    /**
     * 更新密码
     *
     * @param passDto
     * @param principal
     * @return
     */
    @RequestMapping("/updatePass")
    public ResT updatePass(@Validated @RequestBody PassDto passDto, Principal principal) {
        SysUserEntity sysUser = sysUserService.getByUserName(principal.getName());

        boolean matches = bCryptPasswordEncoder.matches(passDto.getCurrentPass(), sysUser.getPassword());
        if (!matches) {
            return ResT.error("旧密码不正确");
        }

        sysUser.setPassword(bCryptPasswordEncoder.encode(passDto.getPassword()));
        sysUser.setUpdateTime(new Date());

        sysUserService.updateById(sysUser);
        return ResT.ok();
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public ResT save(@RequestBody SysUserEntity sysUser) {

        // 默认密码
        String password = bCryptPasswordEncoder.encode(Const.DEFULT_PASSWORD);
        sysUser.setPassword(password);

        sysUser.setStatus(Const.STATUS_ON);

        // 默认头像
        sysUser.setAvatar(Const.DEFULT_AVATAR);

        sysUserService.save(sysUser);

        return ResT.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public ResT update(@RequestBody SysUserEntity sysUser) {
        sysUser.setUpdateTime(new Date());
        sysUserService.updateById(sysUser);

        return ResT.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public ResT delete(@RequestBody String[] pids) {

        sysUserService.removeByIds(Arrays.asList(pids));

        return ResT.ok();
    }

    /**
     * 角色关联
     *
     * @param userPid
     * @param rolePids
     * @return
     */
    @Transactional
    @PostMapping("/role/{userPid}")
//    @PreAuthorize("hasAuthority('sys:user:role')")
    public ResT rolePerm(@PathVariable("userPid") String userPid, @RequestBody String[] rolePids) {

        List<SysUserRoleEntity> userRoles = new ArrayList<>();

        Arrays.stream(rolePids).forEach(r -> {
            SysUserRoleEntity sysUserRole = new SysUserRoleEntity();
            sysUserRole.setRolePid(r);
            sysUserRole.setUserPid(userPid);

            userRoles.add(sysUserRole);
        });

        // 移除之前的权限
        //TODO 待优化 建议之前有的就别删除了
        sysUserRoleService.remove(new QueryWrapper<SysUserRoleEntity>().eq("user_pid", userPid));

        sysUserRoleService.saveBatch(userRoles);
        // 删除缓存
        SysUserEntity sysUser = sysUserService.getById(userPid);
        sysUserService.clearUserAuthorityInfo(sysUser.getUsername());

        return ResT.ok();
    }

}
